package com.glw.sso.platform.web.interceptor;

import com.glw.sso.platform.common.constant.Constant;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@Slf4j
@Component
public class LogInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        MDC.put(Constant.TRACE_UNIQUE_ID, getUniqueId(request));
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        MDC.remove(Constant.TRACE_UNIQUE_ID);
    }

    private String getUniqueId(HttpServletRequest request) {
        String uniqueId4Request = request.getParameter(Constant.TRACE_UNIQUE_ID);
        if (!StringUtils.isEmpty(uniqueId4Request)) {
            return uniqueId4Request;
        }

        String uniqueId4Header = request.getHeader(Constant.TRACE_UNIQUE_ID);
        if (!StringUtils.isEmpty(uniqueId4Header)) {
            return uniqueId4Header;
        }

        return UUID.randomUUID().toString().replace("-", "");
    }
}